<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'

import { ref, nextTick } from 'vue'
import type { Socket } from 'socket.io-client'
import { io } from 'socket.io-client'
import { onMounted, onUnmounted } from 'vue'
import { baseURL } from '../../utils/request'
import { useUserStore } from '../../stores'
import { useRoute } from 'vue-router'

import type { Message, TimeMessages } from '../../types/room'
import { MsgType } from '../../enums'

const store = useUserStore()
const route = useRoute()
const list = ref<Message[]>([])
let socket: Socket
onUnmounted(() => {
  socket.close()
})
onMounted(async () => {
  // 建立链接，创建 socket.io 实例
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      // 订单 ID
      orderId: route.query.orderId
    }
  })

  // socket 原生消息
  socket.on('connect', () => {
    // 建立连接成功
    console.log('connect')
  })
  socket.on('error', (event) => {
    // 错误异常消息
    console.log('error')
  })

  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('disconnect')
  })

  // 后端同学在接口文档中写的： 用来接收医生聊天消息
  socket.on('receiveChatMsg', async (event) => {
    console.log('receiveChatMsg', event)
    list.value.push(event)
    await nextTick()
    window.scrollTo(0, document.body.scrollHeight)
  })
  // 聊天记录
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    console.log('chatMsgList.....')
    // 准备转换常规消息列表
    const arr: Message[] = []
    data.forEach((item) => {
      arr.push({
        id: item.createTime,
        msgType: MsgType.Notify,
        createTime: item.createTime,
        msg: { content: item.createTime }
      })
      arr.push(...item.items)
    })
    // 追加到聊天消息列表
    list.value.unshift(...arr)
    console.log('chatMsgList,,list.value', list.value)
  })
})
const consult = ref()
import { getConsultOrderDetail } from '../../services/consult'
const loadConsult = async () => {
  if (route.query.orderId) {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consult.value = res.data
  }
}
// 一个新的 onMounted
onMounted(() => {
  loadConsult()
})

const sendText = (text: string) => {
  // 发送消息
  const obj = {
    // 发送人
    from: store.user?.id,
    // 收消息人
    to: consult.value?.docInfo?.id,
    // 消息类型
    msgType: MsgType.MsgText,
    // 消息内容
    msg: { content: text }
  }
  console.log(obj)
  socket.emit('sendChatMsg', obj)
}
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <room-status></room-status>
    <room-message :list="list"></room-message>
    <room-action @send-text="sendText"></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);

  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
